<!DOCTYPE html>
<html>

<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">


    <title>用户管理</title>

    <link rel="shortcut icon" href="favicon.ico"> <link href="css/bootstrap.min.css?v=3.3.5" rel="stylesheet">
    <link href="css/font-awesome.min.css?v=4.4.0" rel="stylesheet">

    <!-- Data Tables -->
    <link href="css/plugins/dataTables/dataTables.bootstrap.css" rel="stylesheet">
    <link href="css/animate.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <link href="css/plugins/toastr/toastr.min.css" rel="stylesheet">
    <link href="css/plugins/treeview/bootstrap-treeview.css" rel="stylesheet">
</head>

<body class="gray-bg">
<div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-sm-12">
            <div class="ibox float-e-margins">

                <div class="ibox-content">


                    <table id="datatable" class="table table-striped table-bordered table-hover">
                        <thead>
                        <tr>
                            <th>
                                <button type="button" id="selectAll" class="btn btn-outline btn-primary btn-xs"><i class="fa fa-plus"></i></button>
                                <button type="button" id="selectZero" class="btn btn-outline btn-primary btn-xs"><i class="fa fa-minus"></i></button>
                                <button type="button" id="deleteSelect" class="btn btn-outline btn-danger btn-xs"><i class="fa fa-trash-o"></i></button>
                            </th>
                            <th>id</th>
                            <th>用户名</th>
                            <th>昵称</th>
                            <th>邮箱</th>
                            <th>qq</th>
                            <th>用户类型</th>
                            <th>状态</th>
                            <th>上一次登录时间</th>
                            <th>登录次数</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>

                </div>
            </div>
        </div>
    </div>

    <div class="modal inmodal" id="editModal" tabindex="-1" role="dialog"  aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content animated fadeIn">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                    <div class="modal-title">编辑用户</div>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal form-label-left">
                        <div class="item form-group">
                            <label class="control-label col-md-3 col-sm-3 col-xs-12">用户名：</label>
                            <div class="col-md-6 col-sm-6 col-xs-12">
                                <input type="text" name="username" class="form-control" placeholder="请输入用户名">
                            </div>
                        </div>
                        <div class="item form-group">
                            <label class="control-label col-md-3 col-sm-3 col-xs-12">密码：</label>
                            <div class="col-md-6 col-sm-6 col-xs-12">
                                <input type="text" name="password" class="form-control" placeholder="6位以上">
                            </div>
                        </div>
                        <div class="item form-group">
                            <label class="control-label col-md-3 col-sm-3 col-xs-12">昵称：</label>
                            <div class="col-md-6 col-sm-6 col-xs-12">
                                <input type="text" name="nickname" class="form-control" placeholder="请输入昵称">
                            </div>
                        </div>
                        <div class="item form-group">
                            <label class="control-label col-md-3 col-sm-3 col-xs-12">邮箱：</label>
                            <div class="col-md-6 col-sm-6 col-xs-12">
                                <input type="text" name="email" class="form-control" placeholder="请输入邮箱">
                            </div>
                        </div>
                        <div class="item form-group">
                            <label class="control-label col-md-3 col-sm-3 col-xs-12">QQ：</label>
                            <div class="col-md-6 col-sm-6 col-xs-12">
                                <input type="text" name="qq" class="form-control" placeholder="请输入QQ">
                            </div>
                        </div>

                    </form>
                    <button id="edit" class="btn btn-primary" style="margin-left: 40%;margin-top: 20px;">提交修改</button>

                </div>
            </div>
        </div>
    </div>

    <div class="modal inmodal" id="addModal" tabindex="-1" role="dialog"  aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content animated fadeIn">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                    <div class="modal-title">添加用户</div>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal form-label-left">
                        <div class="item form-group">
                            <label class="control-label col-md-3 col-sm-3 col-xs-12">用户名：</label>
                            <div class="col-md-6 col-sm-6 col-xs-12">
                                <input type="text" name="username" class="form-control" placeholder="请输入用户名">
                            </div>
                        </div>
                        <div class="item form-group">
                            <label class="control-label col-md-3 col-sm-3 col-xs-12">密码：</label>
                            <div class="col-md-6 col-sm-6 col-xs-12">
                                <input type="text" name="password" class="form-control" placeholder="6位以上">
                            </div>
                        </div>
                        <div class="item form-group">
                            <label class="control-label col-md-3 col-sm-3 col-xs-12">昵称：</label>
                            <div class="col-md-6 col-sm-6 col-xs-12">
                                <input type="text" name="nickname" class="form-control" placeholder="请输入昵称">
                            </div>
                        </div>
                        <div class="item form-group">
                            <label class="control-label col-md-3 col-sm-3 col-xs-12">邮箱：</label>
                            <div class="col-md-6 col-sm-6 col-xs-12">
                                <input type="text" name="email" class="form-control" placeholder="请输入邮箱">
                            </div>
                        </div>
                        <div class="item form-group">
                            <label class="control-label col-md-3 col-sm-3 col-xs-12">QQ：</label>
                            <div class="col-md-6 col-sm-6 col-xs-12">
                                <input type="text" name="qq" class="form-control" placeholder="请输入QQ">
                            </div>
                        </div>

                    </form>
                    <button id="add" class="btn btn-primary" style="margin-left: 40%;margin-top: 20px;">添加</button>

                </div>
            </div>
        </div>
    </div>

    <div class="modal inmodal" id="treeModal" tabindex="-1" role="dialog"  aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content animated fadeIn">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                    <div class="modal-title">分配用户角色</div>
                </div>
                <div class="modal-body">
                    <div id="tree"></div>
                    <button id="editUserRoles" class="btn btn-primary" style="margin-left: 40%;margin-top: 20px;">确定</button>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/plugins/jeditable/jquery.jeditable.js"></script>
<script src="js/plugins/dataTables/jquery.dataTables.js"></script>
<script src="js/plugins/dataTables/dataTables.bootstrap.js"></script>
<script src="js/content.js"></script>
<script src="js/plugins/toastr/toastr.min.js"></script>
<script src="js/plugins/treeview/bootstrap-treeview.min.js"></script>
<script src="js/plugins/jsencrypt/jsencrypt.js"></script>
<script type="text/javascript">
    var table;
    var encrypt = new JSEncrypt();
    encrypt.setPublicKey("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCk5QaEr41BfEWIXOsDeB2R9kuBYeoHcfMZvl87HS9F55nC+WGr11YyRdskHloRzYKJhjcce+7fQeKY0MrPXCJG40I5Nu/mRU1W68FXcC3y966LBoIkezkMmLUQ6mDj5oky0kuIR0xeAzE5NGTF7LLAT8H06+uBWX3nHJkR70E0pwIDAQAB");
    $(function(){
        table=  $('#datatable').DataTable({
            ajax: {
                url: '/api/user/listAll'
            },
            pageLength:10,
            lengthMenu:  //自定义分页长度
                [ 10, 20, 50 ]
            ,
            padding:false,
            searching: false,
            ordering:  false,
            dom: '<"top"i>rt<"bottom"flp><"clear">',
            columns: [
                {
                    width:'100px',
                    sClass:"text-center",
                    data: 'id',
                    render:function(id){
                        return '<input type="checkbox" name="select" value="'+id+'" /> ';
                    }
                },
                {
                    width:'50px',
                    data: 'id'
                },
                {sClass:"text-center",data:'username'},
                {sClass:"text-center",data:'nickname'},
                {sClass:"text-center",data:'email'},
                {sClass:"text-center",data:'qq'},
                {sClass:"text-center",data:'userType'},
                {sClass:"text-center",data:'status'},
                {sClass:"text-center",data:'lastLoginTime'},
                {sClass:"text-center",data:'loginCount'},
                {
                    width:'300px',
                    sClass:"text-center",
                    data:'id',
                    render:function(data,type,full){
                        return '<a class="edit btn btn-xs btn-primary" onclick="getContent(' + data + ')" data-toggle="modal" data-target="#editModal" ><i class="fa fa-edit"></i>编辑</a>'+
                            '<a class="btn btn-xs btn-danger btn-remove" onclick="remove(['+data+'])"><i class="fa fa-trash-o"></i>删除</a>'+
                            '<a class="btn btn-xs btn-info btn-allot" data-toggle="modal" data-target="#treeModal" onclick="alterRole('+data+')"><i class="fa fa-circle-thin"></i>分配权限</a>';
                    }
                }
            ]
        });

        $("#datatable_info").before('<button class="btn btn-primary"  data-toggle="modal" data-target="#addModal" onclick="setModalBlank()">添加用户</button>');

        $("#selectAll").click(function(){
            $("input[name='select']").each(function() {
                this.checked = true;
            });
        });
        $("#selectZero").click(function(){
            $("input[name='select']").each(function() {
                this.checked = false;
            });
        });
        $("#deleteSelect").click(function(){
            var ids=[];
            var i=0;
            $("input[name=select]:checked").each(function() {
                ids[i++]=$(this).val();
            });
            remove(ids);
        });

        $("#edit").click(function(){
            var pass=$("#editModal input[name='password']").val();
            if(pass!=null&&pass!='')
                pass=encrypt.encrypt(pass);
            $.ajax({
                url:'/api/user/edit',
                type:'post',
                data:{
                    id:$("body").data("id"),
                    username:$("#editModal input[name='username']").val(),
                    password:pass,
                    nickname:$("#editModal input[name='nickname']").val(),
                    email:$("#editModal input[name='email']").val(),
                    qq:$("#editModal input[name='qq']").val()
                },
                success:function(resp){
                    if(resp.status==200){
                        toastr.success("修改成功");
                        $("#editModal").modal("hide");
                        reloadAll();
                    }else{
                        toastr.error(resp.message);
                    }
                }
            });
        });
        $("#add").click(function(){
            var pass=$("#editModal input[name='password']").val();
            if(pass!=null&&pass!='')
                pass=encrypt.encrypt(pass);
            $.ajax({
                url:'/api/user/add',
                type:'post',
                data:{
                    username:$("#addModal input[name='username']").val(),
                    password:pass,
                    nickname:$("#addModal input[name='nickname']").val(),
                    email:$("#addModal input[name='email']").val(),
                    qq:$("#addModal input[name='qq']").val()
                },
                success:function(resp){
                    if(resp.status==200){
                        toastr.success("添加成功");
                        $("#addModal").modal("hide");
                        reloadAll();
                    }else{
                        toastr.error(resp.message);
                    }
                }
            });
        });

        $("#editUserRoles").click(function(){
            saveUserRole();
            $("#treeModal").modal("hide");
        });
    });


    //重置模态框
    function setModalBlank(){
        $("#addModal input").val("");
    }

    function saveUserRole(){
        var checkeds=$('#tree').treeview('getChecked');
        var ids=[];
        for(var i in checkeds){
            ids.push(checkeds[i].id);
        }
        $.ajax({
            url:'/api/user/saveUserRoles',
            type:'post',
            data:{
                userId:$("body").data("userId"),
                roleIds:ids
            },
        success:function(resp) {
            if(resp.status==200){
                toastr.success("成功修改角色资源权限");
            }else{
                toastr.error("修改角色资源权限失败");
            }
        }
        });
    }

    function alterRole(uid){//获取角色的资源信息
        setTreeView(getRolesWithSelected(uid));
        $("body").data("userId",uid);
    }

    function getRolesWithSelected(uid){
        var data=[];
        $.ajax({
            url:'/api/roles/rolesWithSelected',
            type:'post',
            async:false,
            data:{
                uid:uid
            },
            success:function (resp) {
                if(resp.status==200){
                    var roles=resp.data;
                    for(var i in roles){//构造成bootstrap treview所需的节点格式
                        var r=roles[i];
                        r.text=r.description;
                        if(r.selected==true){
                            r.state=new Object();
                            r.state.checked=true;
                        }
                        data.push(r);
                    }
                }
            }
        });
        return data;
    }

    function setTreeView(treeData){
        $("#tree").treeview({
            data:treeData,
            showCheckbox: true,
            onNodeChecked: function(event, node) {
                function checkedSon(node){
                    for(var i in node.nodes){
                        $('#tree').treeview('checkNode', [node.nodes[i].nodeId]);
                        checkedSon(node.nodes[i]);
                    }
                }
                checkedSon(node);
                var allChecked=true;
                var parent=$('#tree').treeview('getParent', node.nodeId);
                for(var i in parent.nodes){
                    if(parent.nodes[i].state.checked==false){
                        allChecked=false;
                        break;
                    }
                }
                if(allChecked&&parent.nodes!=null&&parent.nodes.length!=0){
                    $('#tree').treeview('checkNode',parent.nodeId);
                }
            },
            onNodeUnchecked: function (event, node) {
                function uncheckedSon(node){
                    for(var i in node.nodes){
                        $('#tree').treeview('uncheckNode', [node.nodes[i].nodeId]);
                        uncheckedSon(node.nodes[i]);
                    }
                }
                uncheckedSon(node);
                var exist=false;
                var parent=$('#tree').treeview('getParent', node.nodeId);
                for(var i in parent.nodes){
                    if(parent.nodes[i].state.checked==true){
                        exist=true;
                        break;
                    }
                }
                if(!exist&&parent.nodes!=null&&parent.nodes.length!=0){
                    $('#tree').treeview('uncheckNode',[parent.nodeId]);
                }
            }
        });
    }

    function reloadAll(){
        $.ajax({
            url:'/api/user/listAll',
            type:'post',
            success:function(resp){
                if(resp.status==200){
                    var currentPage=table.page();
                    table.clear();
                    table.rows.add(resp.data);
                    table.page(currentPage).draw(false);
                    table.page(currentPage).draw(false);//搞不懂为啥要执行两次才跳转。。一次渲染？一次跳转？
                }else{
                    toastr.error("重新加载资源列表失败！");
                }
            }
        });
    }
    function remove(ids){
        console.log("delete" + ids);
        $.ajax({
            url: '/api/user/remove',
            type: 'post',
            data: {
                ids: ids
            },
            success: function (resp) {
                if(resp.status==200) {
                    toastr.success("彻底删除成功");
                    reloadAll();
                }else{
                    toastr.error("操作失败");
                }
            },
            error: function () {
                toastr.error("操作失败");
            }
        });
    }

    function getContent(id){
        console.log("get:"+id);
        $.ajax({
            url:'/api/user/get/'+id,
            type:'post',
            success:function(resp){
                if(resp.status==200){
                    $("#editModal input[name='username']").val(resp.data.username);
                    $("#editModal input[name='password']").val('');
                    $("#editModal input[name='nickname']").val(resp.data.nickname);
                    $("#editModal input[name='email']").val(resp.data.email);
                    $("#editModal input[name='qq']").val(resp.data.qq);
                    $("body").data("id",resp.data.id);
                }else{
                    toastr.error("获取内容失败");
                }
            },
            error:function(){
                toastr.error("请求失败");
            }
        });
    }

</script>


</body>

</html>